<script lang="ts" setup>
import { getUserData as _getUserData, getLevelInfo, changeAvatar } from '@/api/user'
import { useSafeAreaInsets } from '@/mixins/basic'
import UserQrcode from '@/pages/components/user-qrcode'
import { useUserStore } from '@/store/user'
import type { UploadMethod, UploadFile } from 'wot-design-uni/components/wd-upload/types'
import { useUpload } from '@/utils/uploadFile'
import { useMessage } from 'wot-design-uni'

defineOptions({
  options: {
    styleIsolation: 'shared',
  },
})
const props = defineProps({
  // flex 方向
  direction: {
    type: String,
    default: 'row',
  },
})
const message = useMessage()

const userStore = useUserStore()
const { safeAreaInsets } = useSafeAreaInsets()

const fileList = ref([{
	url: userStore.userInfo.avatar
}])

onShow(() => {
	getLevelData()
	getUserData()
})

watch(() => userStore.userInfo.token, (val) => {
	if (val) getUserData()
})
// 次卡用户
const getShowCard = computed(() => {
	if(userStore.userCardInfo.length < 1) return false
	
	return userStore.userCardInfo.find(item => item.count > 0)
})

// 获取等级阶段信息
function getLevelData() {
  getLevelInfo().then((res) => {
    userStore.setLevelArr(res)
  })
}
// 获取用户所有的信息
function getUserData() {
	if (!userStore.userInfo.token) return

	_getUserData().then((res) => {
		userStore.setUserInfo(res.userInfo)
		userStore.setUserCard(res.userCard)
	})
}

// const showQrcode = ref(false)
// 跳转个人资料
function handleProfile() {
  uni.navigateTo({
    url: '/pages-sub/me/profile',
  })
}
// 跳转次卡列表
function handleCard() {
  uni.navigateTo({
    url: '/pages-sub/card/index',
  })
}

// 图片上传变更回调
function handleUploadChange(event) {
	fileList.value = event.fileList
	console.log('event', event)
	const imgUrl = []
	const url_prefix = import.meta.env.VITE_IMG_URL_PREFIX
	fileList.value.forEach((item: any) => {
		// 已上传的
		if (item?.response.length < 1) {
			imgUrl.push(item?.url)
		} else{
			const res = JSON.parse(item.response)
			if (res.code == 0) {
				uni.showToast({
					icon: 'error',
					title: '上传图片失败'
				})
				fileList.value = []
			} else imgUrl.push(url_prefix + res.data.file.url)
		}
	})
	
	console.log('imgUrl', imgUrl)
}
// 自定义上传接口
const customUpload: UploadMethod = (file, formData, options) => {
	// const newFormData = new FormData();
	// // @ts-ignore
	// newFormData.append('image', file.url);
	const uploadTask = uni.uploadFile({
		url: import.meta.env.VITE_UPLOAD_BASEURL,
		header: options.header,
		name: options.name,
		fileName: options.name,
		fileType: options.fileType,
		formData,
		filePath: file.url,
		success(res) {
			if (res.statusCode === options.statusCode) {
				// 设置上传成功
				options.onSuccess(res, file, formData)
			} else {
				// 设置上传失败
				options.onError({ ...res, errMsg: res.errMsg || '' }, file, formData)
			}
		},
		fail(err) {
			// 设置上传失败
			options.onError(err, file, formData)
		}
	})
	// 设置当前文件加载的百分比
	uploadTask.onProgressUpdate((res) => {
		options.onProgress(res, file)
	})
}

function chooseavatar(e) {
	const { avatarUrl } = e.detail 
	console.log('chooseavatar', e)
	userStore.setUserAvatar(avatarUrl)
	uni.showLoading({
		title: '上传中...'
	})
	wx.uploadFile({
		url: import.meta.env.VITE_UPLOAD_BASEURL, // 仅为示例，请替换为你的上传接口地址
		filePath: avatarUrl,
		name: 'file', // 必须填入正确的字段名，这里是示例，请根据后端要求修改
		success(res) {
		  const { code, data } = JSON.parse(res.data);
		  if (code != 1) {
			message.alert({
				title: '提示',
				msg: '上传头像失败，请重试'
			})
		  }
		  // 图片地址
		  const url = import.meta.env.VITE_IMG_URL_PREFIX + data.file.url
		  
		  changeAvatar({
			avatar: url
		  }).then(res => {
		  	uni.showToast({
		  		icon: 'none',
		  		title: '上传头像成功'
		  	})
		  })
		  
		  // 处理上传成功的逻辑，例如更新用户信息等
		  console.log('upload success:', res);
		},
		fail(err) {
		  console.error('upload failed:', err);
		  message.alert({
			  title: '提示',
			  msg: '上传头像失败，请重试'
		  })
		},
		complete() {
			uni.hideLoading()
		}
	});
}
</script>

<template>
  <view class="user-box" :class="[`flex-${props.direction}`]" :style="props.direction === 'column' ? { 'padding-top': `${safeAreaInsets.top + 68}px` } : ''">
    <!-- 背景色 -->
    <image class="bg-img" webp src="/static/images/user_bg.jpg" />

    <view class="user-avatar">
<!-- 	<wd-upload
		custom-class='avatar'
		:file-list="fileList"
		multiple
		reupload
		:disabled="props.direction !== 'column'"
		image-mode="aspectFill"
		:limit="1"
		@change="handleUploadChange"
		:upload-method="customUpload"
	>
		<view custom-class="avatar"></view>
	</wd-upload> -->
	<button v-if="props.direction === 'column'" class="avatar-wrapper" open-type="chooseAvatar" @chooseavatar="chooseavatar">
		<image class="avatar" :src="userStore.userInfo.avatar"></image>
	</button> 
	<wd-img v-else custom-class="avatar" round :src="userStore.userInfo.avatar">
		<template #error>
		  <view class="error-wrap">
			加载失败
		  </view>
		</template>
		<template #loading>
		  <view class="loading-wrap">
			<wd-loading />
		  </view>
		</template>
	</wd-img>
      <!-- 用户二维码 -->
      <!-- <view v-if="userStore.userInfo.token" class="qrcode-box" @click="showQrcode = true">
				<image class="qrcode" src="/src/static/images/qrcode.webp" />
			</view> -->
      <!-- 用户二维码 -->
      <UserQrcode v-if="userStore.userInfo.token" />
    </view>

    <!-- 用户昵称、用户等级 -->
    <view class="user-info">
      <!-- 未登录状态 -->
      <view v-if="!userStore.userInfo.token" class="no-login">
        <wd-button type="text" open-type="getPhoneNumber" custom-class="user-name" @getphonenumber="userStore.handleLogin">
          点击登录
        </wd-button>
      </view>
      <template v-else>
        <view v-if="props.direction === 'row'" class="user-name f-i-c">
          <text>{{ userStore.userInfo.nickname }}</text>
          <image class="icon" webp src="/src/static/images/setting.png" @click="handleProfile" />
        </view>

        <view class="user-tag f-i-c">
          <view class="user-tag-item level">
            <image class="icon" webp src="/src/static/images/level.png" />
            <text>{{ userStore.getUserLevel }}</text>
          </view>

          <view v-if="getShowCard" class="user-tag-item card" @click="handleCard">
            <image class="icon" webp src="/src/static/images/card.png" />
            <text>次卡用户</text>
          </view>
        </view>
      </template>
    </view>
  </view>
</template>

<style lang="scss" scoped>
.user-box {
  // background-image: url('/static/images/user_bg.webp');
  // background-repeat: no-repeat;
  // background-position: center;
  // background-size: 100%;
  position: relative;
  display: flex;

  &.flex-row {
    padding: 99px 26px 0 26px;

    // .user-avatar {
    // 	.qrcode-box {
    // 		width: 24px;
    // 		height: 24px;

    // 		.qrcode {
    // 			width: 14px;
    // 			height: 14px;
    // 		}
    // 	}
    // }

    .user-info {
      padding-left: 18px;
      .user-tag {
        padding-top: 15px;
        &-item {
        }
      }
    }
  }
  &.flex-column {
    flex-direction: column;
    justify-content: center;
    align-items: center;
    .user-avatar {
      width: 118px;
      height: 118px;
      :deep(.avatar) {
        width: 118px;
        height: 118px;
      }

      :deep(.qrcode-box) {
        width: 34px;
        height: 34px;

        .qrcode {
          width: 20px;
          height: 20px;
        }
      }
    }

    .user-info {
      .user-tag {
        padding-top: 21px;
        &-item {
        }
      }
    }
  }

  .bg-img {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    height: 247px;
    background: linear-gradient(180deg, rgba(247, 192, 153, 1), rgba(247, 192, 153, 0) 100%);
    z-index: -1;
  }

  .user-avatar {
    flex-shrink: 0;
    position: relative;
    width: 80px;
    height: 80px;
	.avatar-wrapper {
		padding: 0;
		border: 0;
		border-radius: 50%;
		box-shadow: 0px 8px 16px 0px rgba(241, 213, 179, 1);
		&::after {
			border: 0;
		}
	}
    :deep(.avatar) {
      width: 80px;
      height: 80px;
      background-color: #fff;
      box-shadow: 0px 8px 16px 0px rgba(241, 213, 179, 1);
	  border-radius: 50%;
		.wd-upload__preview {
			width: 100%;
			height: 100%;
			margin: 0;
		  
			.wd-upload__picture {
				border-radius: 50%;
			}
		  
			.wd-upload__close {
				display: none;
			}
		}
    }
    :deep(.error-wrap) {
      height: 100%;
      display: flex;
      justify-content: center;
      align-items: center;
      font-size: 12px;
    }
    // .qrcode-box {
    // 	border-radius: 50%;
    // 	position: absolute;
    // 	right: 0;
    // 	bottom: 0;
    // 	box-shadow: 0px 5px 16px 0px rgba(0, 0, 0, 0.08);
    // 	background-color: #fff;
    // 	display: flex;
    // 	justify-content: center;
    // 	align-items: center;
    // }
  }

  .user-info {
    flex: 1;
    :deep(.user-name) {
      padding-top: 14px;
      font-size: 20px;
      font-weight: 500;
      line-height: 20px;
      color: $uni-main-color;
      .icon {
        margin-left: 8px;
        width: 22px;
        height: 22px;
      }
    }

    .user-tag {
      &-item {
        border-radius: 15px;
        padding: 0 9px;
        height: 30px;
        align-items: center;
        font-size: 13px;
        font-weight: 600;
        line-height: 18px;
        box-shadow: 0px 4px 10px 0px rgba(241, 213, 179, 1);
        display: flex;
        align-items: center;
        > text {
          padding-left: 8px;
        }

        &.level {
          background: linear-gradient(180deg, rgba(255, 249, 238, 1), rgba(251.25, 237, 212.25, 1) 100%);
          color: #eeb041;

          .icon {
            width: 24px;
            height: 24px;
          }
        }

        &.card {
          background: linear-gradient(180deg, rgba(238, 254, 255, 1), rgba(212, 232, 251, 1) 100%);
          color: #337ca8;
          .icon {
            width: 20px;
            height: 16.6px;
          }
        }

        & + .user-tag-item {
          margin-left: 10px;
        }
      }
    }
  }
}
</style>
